import React, { useEffect, useState } from 'react';
import { Form, Input, Switch, Collapse, InputNumber, message, Radio, Slider } from 'antd';
// import { CaretRightOutlined } from '@ant-design/icons';
import styles from './index.module.scss';
import { filterObjectNullKeys } from 'src/libs/utils';
import InputColorPicker from 'src/pages/AnalyseManage/EditReport/components/EditorStyleType/InputColorPicker';
import Editor from 'src/pages/AnalyseManage/EditReport/components/EditorStyleType/Editor';
import Border from 'src/pages/AnalyseManage/EditReport/components/EditorStyleType/Border';
import UploadComponent from 'src/pages/AnalyseManage/EditReport/components/Common/UploadComponent';
import ChooseImage from 'src/pages/AnalyseManage/EditReport/components/Common/ChooseImage';
import { deleteFile } from 'src/services/AnalyseManage';

const { Item: FormItem } = Form;
const { Panel } = Collapse;

const PageEditor = ( props: any ) => {
	const { config, onValuesChange, comps, onAllValuesChange } = props;
	const [ form ] = Form.useForm();
	
	const [ chartBackgroundColor, setChartBackgroundColor ] = useState(
		config.chartBackgroundColor || 'rgba(134,188,37,1)'
	);
	const [ chartTitleBackColor, setChartTitleBackColor ] = useState( config.titleBg || 'rgba(134,188,37,1)' );


	const mainTitleBackColorDefault = config.mainTitleBackColor ? config.mainTitleBackColor : 'rgba(134,188,37,1)';
	const allBackgroundColorDefault = config.allBackgroundColor ? config.allBackgroundColor : '#f0f3f4';

	const [ titleBgColor, setTitleBgColor ] = useState( mainTitleBackColorDefault );
	const [ backgroundColor, setBackgroundColor ] = useState( allBackgroundColorDefault );

	//	背景设置选项
	const [ backgroundSetting, setBackgroundSetting ] = useState( config.backgroundSetting || 1 );

	//	上传文件
	const [ fileList, setFileList ] = useState( config.backgroundImage || [] );

	//	设置背景图片伸缩方式
	const [ backgroundImageStyle, setBackgroundImageStyle ] = useState( config.backgroundImageStyle || 1 );

	//	背景图片模糊度
	const [ bgImgBlur, setBgImgBlur ] = useState( config.bgImgBlur || 0 );

	//	背景图片透明度
	const [ bgImgOpacity, setBgImgOpacity ] = useState( config.bgImgOpacity || 10 );

	const [ timer, setTimer ] = useState();


	const initChooseImage = [
		'https://bdh-document.oss-cn-hangzhou.aliyuncs.com/common/bi_bg/001.jpg',
		'https://bdh-document.oss-cn-hangzhou.aliyuncs.com/common/bi_bg/002.jpg',
		'https://bdh-document.oss-cn-hangzhou.aliyuncs.com/common/bi_bg/003.jpg',
		'https://bdh-document.oss-cn-hangzhou.aliyuncs.com/common/bi_bg/004.jpg',
		'https://bdh-document.oss-cn-hangzhou.aliyuncs.com/common/bi_bg/005.jpg',
		'https://bdh-document.oss-cn-hangzhou.aliyuncs.com/common/bi_bg/006.jpg',
		'https://bdh-document.oss-cn-hangzhou.aliyuncs.com/common/bi_bg/007.jpg',
		'https://bdh-document.oss-cn-hangzhou.aliyuncs.com/common/bi_bg/008.jpg'
	];

	// console.log( props );
	// const [ titleFontColor, setTitleFontColor ] = useState( config.titleFontColor || '#333' );
	// const [ chartBorderShadowColor, setChartBorderShadowColor ] = useState(
	// 	config.chartBorderShadowColor || '#333'
	// );
	// const [ chartBorderColor, setChartBorderColor ] = useState( config.chartBorderColor || '#f2f2f2' );

	const handleValuesChange = () => {
		console.log( config.allBackgroundColor, backgroundColor );
		form.validateFields().then( async ( values: any ) => {
			if ( onValuesChange ) {
				const value = filterObjectNullKeys( {
					...values,
					// mainTitleBackColor: titleBgColor,
					// allBackgroundColor: backgroundColor,
				} );
				console.log( 'changed', values, titleBgColor, backgroundColor );
				onValuesChange( config.type, config.key, value );
			}
		} );
	};

	const handleCommonValuesChange = ( changedValues ) => {
		form.validateFields().then( async ( values: any ) => {
			if ( onValuesChange ) {
				const value = filterObjectNullKeys( {
					...config,
				} );

				if ( changedValues ) {
					updateCompsConfig( changedValues, value );
				} else {
					onValuesChange( config.type, config.key, value );
				}
			}
		} );
	};

	const onCommonValuesChange = ( type: string, key: string, values: Object ) => {
		handleCommonValuesChange( values );
	};

	// 更改子项的相关配置 标题部分 边框部分
	const updateCompsConfig = ( values, pageConfig? ) => {
		const newComps = comps.map( ( item ) => {
			return { ...item, style: { ...item.style, ...values } };
		} );
		pageConfig = { ...config, ...pageConfig, ...values };

		onAllValuesChange( newComps, pageConfig );
	};

	// 设置大标题背景色
	const handleChangeTitleBgColorComplete = ( color ) => {
		setTitleBgColor( color );
		onValuesChange( config.type, config.key, { mainTitleBackColor: color } );
	};

	// 设置整体背景颜色
	const handleChangeBgColorComplete = ( color ) => {
		setBackgroundColor( color );
		onValuesChange( config.type, config.key, { allBackgroundColor: color } );
		// handleValuesChange();
	};
	// 设置报表背景色
	const handleChangeChartBackColorComplete = ( color ) => {
		setChartBackgroundColor( color );
		updateCompsConfig( { chartBackgroundColor: color } );
	};

	// 设置报表标题背景色
	const handleChangeChartBackTitleColorComplete = ( color ) => {
		setChartTitleBackColor( color );
		updateCompsConfig( { titleBg: color } );
	};

	//	删除背景图片
	const handleDelete = async ( file ) => {
		const info = await deleteFile( file );

		if ( info.status === 1 ) {
			message.success( '删除成功' );
			const imageList = [];
			onValuesChange( config.type, config.key, { backgroundImage: imageList } );
			setFileList( imageList );
		}

	};

	const handleRadioChange = ( event ) => {
		setBackgroundSetting( event.target.value );
		onValuesChange( config.type, config.key, { backgroundImage: [], backgroundSetting: event.target.value } );
		setFileList( [] );
	};

	//	设置背景图片
	const handleUpload = ( imageList ) => {
		onValuesChange( config.type, config.key, { backgroundImage: imageList } );
		setFileList( imageList );
	};

	const handleBgImageStyleChange = ( event ) => {
		setBackgroundImageStyle( event.target.value );
		onValuesChange( config.type, config.key, { backgroundImageStyle: event.target.value } );
	};

	//	选择图片
	const handleChooseImage = ( img ) => {
		setFileList( [ { url: img } ] );
		onValuesChange( config.type, config.key, { backgroundImage: [ { url: img } ] } );
	};

	const handleSliderChange = ( name, value ) => {
		if( name === 'bgImgBlur' ) {
			setBgImgBlur( value );
		} else {
			setBgImgOpacity( value );
		}

		if( timer ) clearTimeout( timer );
		let newTimer = setTimeout( () => {
			onValuesChange( config.type, config.key, { [ name ]: value } );
		}, 500 );

		setTimer( newTimer );

	};

	//	必传的参数，用户服务端根据参数新建资源路径
	const requestData = {
		moduleName: 'bi',
		pageId: config.id,
		imageChartId: config.key
	};

	useEffect( () => {
		setBgImgBlur( config.bgImgBlur || 0 );
		setBgImgOpacity( config.bgImgOpacity || 10 );
		setBackgroundImageStyle( config.backgroundImageStyle || 1 );
		setBackgroundSetting( config.backgroundSetting || 1 );
		setFileList( config.backgroundImage || [] );
	}, [ setBgImgBlur, config.bgImgBlur,
		setBgImgOpacity, config.bgImgOpacity,
		setBackgroundImageStyle, config.backgroundImageStyle,
		setBackgroundSetting, config.backgroundSetting,
		setFileList, config.backgroundImage ] );

	return (
		<div className={styles.control_container}>
			{/* expandIcon={( { isActive } ) => <CaretRightOutlined rotate={isActive ? 90 : 0} />} */}
			<Collapse ghost className="site-collapse-custom-collapse">
				<Panel header="标题" key="title">
					<Form
						layout="horizontal"
						size="small"
						form={form}
						onValuesChange={handleValuesChange}
						initialValues={config}
					>
						<FormItem name="showHeader" label="发布后是否显示标题" valuePropName="checked">
							<Switch defaultChecked={true} checked={config.showHeader}></Switch>
						</FormItem>
						<FormItem name="name" label="标题内容">
							<Input />
						</FormItem>
						<FormItem label="字体">
							<Editor
								//	页面的config数据结构与图表的数据结构不同，所以在设置字体时，页面的样式在config中，图表的样式在config.style中，所以为了保持统一
								config={ { style: config, key: config.key, type: config.type } }
								form={form}
								onValuesChange={onValuesChange}
								fontFamilyName="mainTitleFontFamily"
								fontSizeName="mainTitleFontSize"
								fontColorName="mainTitleFontColor"
								boldName="mainTitleIsBold"
								italicName="mainTitleIsItalic"
								underLineName="mainTitleIsUnderLine"
								alignHorName="mainTitleAlignHor"
								alignVerName="mainTitleAlignVer"
							/>
						</FormItem>

						<FormItem name="mainTitleHeight" label="标题框高度">
							<InputNumber
								value={config.mainTitleHeight}
								min={0}
								style={{ width: '100%' }}
							/>
						</FormItem>
						<FormItem name="mainTitleBackColor" label="标题背景色">
							<InputColorPicker
								color={titleBgColor}
								change={handleChangeTitleBgColorComplete}
							></InputColorPicker>
						</FormItem>

						{/* <FormItem name="titleFontSize" label="字体大小">
							<InputNumber min={10} />
						</FormItem>
						<FormItem name="titleFontColor" label="字体颜色">
							<InputColorPicker
								color={titleFontColor}
								change={handleChangeTitleFontColorComplete}
							></InputColorPicker>
						</FormItem>
						<FormItem name="titleTextItalic" label="是否斜体">
							<Switch checked={config.titleTextItalic}></Switch>
						</FormItem>
						<FormItem name="titleTextBold" label="是否加粗">
							<Switch checked={config.titleTextBold}></Switch>
						</FormItem>
						<FormItem name="titleTextUnderline" label="是否下划线">
							<Switch checked={config.titleTextUnderline}></Switch>
						</FormItem>
						<FormItem name="titleTextAlign" label="标题水平">
							<Radio.Group buttonStyle="solid">
								<Radio.Button value="flex-start">左</Radio.Button>
								<Radio.Button value="center">中</Radio.Button>
								<Radio.Button value="flex-end">右</Radio.Button>
							</Radio.Group>
						</FormItem>
						<FormItem name="titleTextUpDown" label="标题上下">
							<Radio.Group buttonStyle="solid">
								<Radio.Button value="flex-start">上</Radio.Button>
								<Radio.Button value="center">中</Radio.Button>
								<Radio.Button value="flex-end">下</Radio.Button>
							</Radio.Group>
						</FormItem>*/}
					</Form>
				</Panel>
				<Panel header="背景颜色" key="background">
					<Form form={form} onValuesChange={handleValuesChange} initialValues={config}>
						<FormItem label="报表背景设置" labelCol={ { span: 24 } }>
							<Radio.Group value={backgroundSetting} defaultValue={backgroundSetting} onChange={handleRadioChange}>
								<Radio value={1} style={ { display: 'block' } }>内置背景图片</Radio>
								<Radio value={2} style={ { display: 'block' } }>上传背景图片</Radio>
								<Radio value={3} style={ { display: 'block' } }>只使用背景色</Radio>
							</Radio.Group>
						</FormItem>

						{
							backgroundSetting === 1 && (
								<ChooseImage fileList={ fileList } initChooseImage={initChooseImage} handleChooseImage={handleChooseImage}></ChooseImage>
							)
						}

						{
							backgroundSetting === 2 && (
								<FormItem
									labelAlign="left" labelCol={ { span: 8 } } wrapperCol={ { span: 24 } } label="报表背景图片">
									<UploadComponent
										fileList={ fileList }
										requestData={requestData}
										handleUpload={ ( imageList ) => handleUpload( imageList ) }
										handleDelete={ ( imageList ) => handleDelete( imageList ) }></UploadComponent>
								</FormItem>
							)
						}

						{
							backgroundSetting === 3 && (
								<FormItem name="allBackgroundColor" label="报表背景颜色">
									<InputColorPicker
										color={backgroundColor}
										change={handleChangeBgColorComplete}
									></InputColorPicker>
								</FormItem>
							)
						}

						{
							backgroundSetting !== 3 && (
								<>
									<FormItem label="背景图缩放方式" labelCol={ { span: 24 } }>
										<Radio.Group value={backgroundImageStyle} defaultValue={backgroundImageStyle} onChange={handleBgImageStyleChange}>
											<Radio value={1} style={ { display: 'block' } }>拉伸铺满</Radio>
											<Radio value={2} style={ { display: 'block' } }>水平拉伸铺满，垂直重复</Radio>
											<Radio value={3} style={ { display: 'block' } }>垂直拉伸铺满，水平重复</Radio>
											<Radio value={4} style={ { display: 'block' } }>不拉伸，水平垂直重复</Radio>
										</Radio.Group>
									</FormItem>

									<FormItem label="背景图片模糊度">
										<Slider
											marks={ { 0: 0, 10: 10, 20: 20 } } max={20} defaultValue={bgImgBlur} value={bgImgBlur}
											onChange={( value ) => handleSliderChange( 'bgImgBlur', value )}/>
									</FormItem>

									<FormItem label="背景图片透明度">
										<Slider
											marks={ { 0: 0, 5: 5, 10: 10 } } max={10} defaultValue={bgImgOpacity} value={bgImgOpacity}
											onChange={( value ) => handleSliderChange( 'bgImgOpacity', value )}/>
									</FormItem>
								</>

							)
						}

					</Form>
				</Panel>

				<Panel header="图表管理" key="charts">
					<Form
						form={form}
						onValuesChange={handleCommonValuesChange}
						initialValues={config}
						size="small"
					>
						<FormItem name="chartBackgroundColor" label="背景色">
							<InputColorPicker
								color={chartBackgroundColor}
								change={handleChangeChartBackColorComplete}
							></InputColorPicker>
						</FormItem>
						<FormItem name="chartBackgroundOpacity" label="透明度">
							<InputNumber
								defaultValue={config.chartBackgroundOpacity}
								min={0}
								max={100}
							/>
						</FormItem>
						<FormItem name="chartTitleBackColor" label="标题背景色">
							<InputColorPicker
								color={chartTitleBackColor}
								change={handleChangeChartBackTitleColorComplete}
							></InputColorPicker>
						</FormItem>
						<FormItem name="chartFont" label="字体">
							<Editor
								config={config}
								form={form}
								onValuesChange={onCommonValuesChange}
								fontFamilyName="titleFontFamily"
								fontSizeName="titleFontSize"
								fontColorName="titleFontColor"
								boldName="titleIsBold"
								italicName="titleIsItalic"
								underLineName="titleIsUnderLine"
								alignHorName="titleAlignHor"
								alignVerName="titleAlignVer"
							/>
						</FormItem>
						<Border
							config={config}
							form={form}
							onValuesChange={onCommonValuesChange}
						></Border>

					</Form>
				</Panel>
			</Collapse>
		</div>
	);
};

export default React.memo( PageEditor );
